﻿/// Write a program that reads a rectangular matrix of size N x M and finds in it the square 3 x 3 that has maximal sum of its elements.



using System;

class zad2
{
    static void Main()
    {
        

        //int[,] matrix = new int[n, m];
        int[,] matrix = 
		{
			{0, 2, 4, 0, 9, 5},
			{7, 1, 3, 3, 2, 1},
			{1, 3, 9, 8, 5, 6},
			{4, 6, 7, 9, 1, 0},
		};

        int n = matrix.GetLength(0);
        int m = matrix.GetLength(1);

        int bestSum = Int32.MinValue;
        int bestRow = 0;
        int bestCol = 0;
        

        for (int i = 0; i < n; i++)
        {
            int sum = 0;
            
            for (int j = 0; j < m; j++)
            {
                sum =  HitCount(matrix, i, j);
              
                if (sum > bestSum)
                {
                    bestSum = sum;
                    bestRow = i;
                    bestCol = j;
                }
            }
            
        }

        Console.WriteLine("best sum = {0}, for element {1}, {2} ", bestSum, bestRow, bestCol);
    }


    static int HitCount(int[,] array, int row, int col)
    {
        int result = 0;
        int startRow = Math.Max(row - 1, 0);
        int finRow = Math.Min(row + 1, array.GetLength(0) - 1);
        int finCol = Math.Min(col + 1, array.GetLength(1) - 1);
        int startCol = Math.Max(col - 1, 0);

        for (int i = startRow; i <= finRow; i++)
        {
            for (int j = startCol; j <= finCol; j++)
            {
                  result +=  array[i, j];
            }
        }
        return result;
    }

}

